package com.hmdp.service.impl;

import com.hmdp.constant.StatusConstant;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

import static com.hmdp.constant.OtherConstant.ORDER;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private ISeckillVoucherService seckillVoucherService;
//    @Autowired
//    StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public Result seckillVoucher(Long voucherId) {
        //1.查詢優惠券信息
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        //2.判斷秒殺是否開始
        LocalDateTime beginTime = voucher.getBeginTime();
        if (beginTime.isAfter(LocalDateTime.now())) {
            return Result.fail(StatusConstant.ACTIVITY_NOT_START);
        }
        LocalDateTime endTime = voucher.getEndTime();
        if (endTime.isBefore(LocalDateTime.now())) {
            return Result.fail(StatusConstant.ACTIVITY_END);
        }
        //2.2是，判斷是否是否存在庫存
        Integer stock = voucher.getStock();
        //2.2.1否，返回錯誤信息
        if (stock <= 0) {
            return Result.fail(StatusConstant.VOUCHER_NOT_ENOUGH);
        }

        UserDTO user = UserHolder.getUser();
        Long userId = UserHolder.getUser().getId();
        //根據優惠券id和用戶id查詢訂單
        Integer count = query().eq("voucher_id", voucherId).eq("user_id", userId).count();

        //判斷是否存在訂單
        if (count > 0) {
            return Result.fail(StatusConstant.VOUCHER_ORDER_EXIST);
        }
//        SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        boolean isLock = lock.tryLock();
        if (!isLock) {
            return Result.fail(StatusConstant.VOUCHER_ORDER_EXIST);
        }

        try {

            return createVouchOrder(voucherId);
        } finally {
            lock.unlock();
        }
    }

    @Transactional
   public Result createVouchOrder(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        //2.2.2是，扣除庫存，創建訂單,返回訂單id

        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId).update();
        if (!success) {
            return Result.fail(StatusConstant.VOUCHER_NOT_ENOUGH);
        }

        VoucherOrder voucherOrder = new VoucherOrder();
        long orderId = redisIdWorker.nextId(ORDER);
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);

        return Result.ok(orderId);
    }

}
